import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_yyt/models/medcical_recent_entity.dart';
import 'package:ls_work/a_yyt/models/medical_elder_entity.dart';
import 'package:ls_work/a_yyt/models/pending_selected_group_entity.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/chart_line/line_chart_page.dart';
import 'package:ls_work/widgets/load_image.dart';

class HealthFilePage extends StatefulWidget {
  final MedicalElderInfo? info;
  HealthFilePage({Key? key, this.info});
  @override
  _HealthFilePageState createState() => _HealthFilePageState();
}

class _HealthFilePageState extends State<HealthFilePage> {
  List<MedicalElderInfo> chipMedicalList = [];
  List<MedicalElderInfo> dataList = [];
  List<ChartData> dataChartList = [];
  List<PendingSelectedGroupEntity>? chipDateList;
  int medcialId = 7;
  int queryTimeType = 1;
  int _maxYValue = 180;
  int _minYValue = 30;
  int _yCount = 10;
  List<Color> gradientColors = [
    const Color(0xff23b6e6),
    const Color(0xff02d39a),
  ];
  List<String> imageNameUrl = [
    'home/h_xueya',
    'home/h_xinlv',
    'home/h_xueyang',
    'home/h_xuetang',
    'home/h_tiwen',
    'home/h_tizhong',
    'home/h_niaoliang',
    'home/h_yinshui',
  ];
  @override
  void initState() {
    super.initState();
    chipDateList = [
      PendingSelectedGroupEntity(isSelected: true, id: 1, name: '今天'),
      PendingSelectedGroupEntity(isSelected: false, id: 2, name: '近7天'),
      PendingSelectedGroupEntity(isSelected: false, id: 3, name: '近14天'),
      PendingSelectedGroupEntity(isSelected: false, id: 4, name: '近30天'),
    ];
    chipMedicalList = [
      MedicalElderInfo(
        isSelected: true,
        dataTypeId: 0,
        name: '血压',
        numberConcat: '',
        collectionTime: '',
        unit: 'mmHg',
      ),
      MedicalElderInfo(
        isSelected: false,
        dataTypeId: 3,
        name: '心率',
        numberConcat: '',
        collectionTime: '',
        unit: '次/分',
      ),
      MedicalElderInfo(
        isSelected: false,
        dataTypeId: 4,
        name: '血氧',
        numberConcat: '',
        collectionTime: '',
        unit: '%',
      ),
      MedicalElderInfo(
        isSelected: false,
        dataTypeId: 11,
        name: '血糖',
        numberConcat: '',
        collectionTime: '',
        unit: '',
      ),
      MedicalElderInfo(
        isSelected: false,
        dataTypeId: 6,
        name: '体温',
        numberConcat: '',
        collectionTime: '',
        unit: '℃',
      ),
      MedicalElderInfo(
        isSelected: false,
        dataTypeId: 2,
        name: '体重',
        numberConcat: '',
        collectionTime: '',
        unit: 'kg',
      ),
      // MedicalElderInfo(
      //   isSelected: false,
      //   dataTypeId: 20,
      //   name: '尿量',
      //   numberConcat: '',
      //   collectionTime: '',
      //   unit: '',
      // ),
      // MedicalElderInfo(
      //   isSelected: false,
      //   dataTypeId: 19,
      //   name: '饮水',
      //   numberConcat: '',
      //   collectionTime: '',
      //   unit: '',
      // ),
    ];

    WidgetsBinding.instance.addPostFrameCallback((_) {
      /// 接口请求
      _fectData();
      _fectHistoryData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.bg_color,
      appBar: AppBar(
        title: Text('健康档案'),
        elevation: 0.5,
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              margin: EdgeInsets.only(top: 10, left: 20, right: 20),
              padding: EdgeInsets.all(15),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text(
                    '${widget.info?.name??""}    ',
                    style: TextStyles.textDark18,
                  ),
                  Expanded(
                    child: Text(
                      '${widget.info?.roomNo??""}    ',
                      style: TextStyles.textGray16,
                    ),
                  ),
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
              height:
                  ((ScreenUtil.getScreenW(context) - 40) / 2) / 1.5 * 3 + 30,
              child: GridView.builder(
                physics: new NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2, //每行三列
                  childAspectRatio: 1.5, //显示区域宽高相等
                ),
                itemCount: chipMedicalList.length,
                itemBuilder: (context, index) {
                  return Container(
                    decoration: BoxDecoration(
                      color: chipMedicalList[index].isSelected == true
                          ? Colors.orange[50]
                          : Colors.white,
                      border: Border.all(
                        color: chipMedicalList[index].isSelected == true
                            ? Colors.orange[200]!
                            : Colours.line,
                        width: 0.5,
                      ),
                    ),
                    alignment: Alignment.center,
                    child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        if (chipMedicalList[index].isSelected == true) return;

                        setState(() {
                          if (index == 0) {
                            _maxYValue = 180;
                            _minYValue = 0;
                            _yCount = 9;
                          } else if (index == 1) {
                            _maxYValue = 160;
                            _minYValue = 0;
                            _yCount = 8;
                          } else if (index == 2) {
                            _maxYValue = 100;
                            _minYValue = 0;
                            _yCount = 5;
                          } else if (index == 3) {
                            _maxYValue = 14;
                            _minYValue = 2;
                            _yCount = 7;
                          } else if (index == 4) {
                            _maxYValue = 45;
                            _minYValue = 30;
                            _yCount = 5;
                          } else if (index == 5) {
                            _maxYValue = 200;
                            _minYValue = 0;
                            _yCount = 10;
                          }
                          for (var item in chipMedicalList) {
                            if (item.dataTypeId ==
                                chipMedicalList[index].dataTypeId) {
                              chipMedicalList[index].isSelected = true;
                              medcialId = chipMedicalList[index].dataTypeId??0;
                              _fectHistoryData();
                            } else {
                              item.isSelected = false;
                            }
                          }
                        });
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          LoadAssetImage(imageNameUrl[index]),
                          Gaps.hGap10,
                          Container(
                            height: 50,
                            width: 0.5,
                            color: Colours.line,
                          ),
                          Gaps.hGap10,
                          Column(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              Text(
                                (chipMedicalList[index].unit??"").isNotEmpty
                                    ? '${chipMedicalList[index].name}(${chipMedicalList[index].unit})'
                                    : chipMedicalList[index].name??"",
                              ),
                              Text('${chipMedicalList[index].numberConcat}'),
                              Text(
                                (chipMedicalList[index].collectionTime??"").isNotEmpty
                                    ? DateUtil.formatDateStr(
                                        chipMedicalList[index].collectionTime??"",
                                        format: DateFormats.mo_d_h_m,
                                      )
                                    : '',
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(20, 0, 20, 15),
              child: Wrap(
                spacing: 10,
                children: (chipDateList??[]).map(
                  (f) {
                    return ChoiceChip(
                      label: Text(f.name??""),
                      selected: f.isSelected==true,
                      selectedColor: Colours.app_main,
                      disabledColor: Colours.bg_color,
                      onSelected: (bool value) {
                        setState(
                          () {
                            if (value) {
                              for (var item in (chipDateList??<PendingSelectedGroupEntity>[])) {
                                if (item.id == f.id) {
                                  item.isSelected = true;
                                  queryTimeType = item.id??0;
                                  _fectHistoryData();
                                } else {
                                  item.isSelected = false;
                                }
                              }
                            }
                          },
                        );
                      },
                    );
                  },
                ).toList(),
              ),
            ),
            Container(
              child: LineChart(
                ScreenUtil.getScreenW(context),
                300,
                xOffset: 0.0,
                showBaseline: true,
                maxYValue: _maxYValue,
                minYValue: _minYValue,
                yCount: _yCount,
                dataList: dataChartList,
              ),
            ),
          ],
        ),
      ),
    );
  }

  _fectData() {
    var map = {'customerId': widget.info?.id};

    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.getRecentlyHealthRecordByCustomer}',
            data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        //
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            MedicalRecentModel model = MedicalRecentModel.fromJson(map);
            setState(() {
              for (var item in (model.data??<MedicalElderInfo>[])) {
                for (var item2 in chipMedicalList) {
                  if (item2.dataTypeId == item.dataTypeId) {
                    item2.numberConcat = item.number.toString();
                    item2.collectionTime = item.collectionTime;
                    if ((item2.unit??"").isEmpty) item2.unit = item.unit;
                    // chipMedicalList[chipMedicalList.indexOf(item2)] = item2;
                  }
                }
              }
              for (var item in (model.data??<MedicalElderInfo>[])) {
                if (item.dataTypeId == 7) {
                  chipMedicalList[0].collectionTime = item.collectionTime;
                  chipMedicalList[0].numberConcat = "${chipMedicalList[0].numberConcat??""}${item.number.toString()}";
                }
              }
              for (var item in (model.data??<MedicalElderInfo>[])) {
                if (item.dataTypeId == 8) {
                  chipMedicalList[0].collectionTime = item.collectionTime;
                  chipMedicalList[0].numberConcat = "${chipMedicalList[0].numberConcat??""}/${item.number.toString()}";

                }
              }
            });
            // ///1-身高；2-体重；3-心率；4-血氧；5-脉率；6-体温；7-低压；8-高压；9-呼吸；10-大便
            // for (var item in protocolLis) {
            //   if (item.dataTypeId == 1) {}
            // }
            // setState(() {});
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  _fectHistoryData() {
    var map = {
      'page': 1,
      'rows': 100,
      'customerId': widget.info?.id,
      'dataTypeId': medcialId,
      'queryTimeType': queryTimeType,
    };

    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.getHealthRecord}', data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        print(map);
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            dataChartList.clear();
            MedicalElderModel model = MedicalElderModel.fromJson(map['data']);
            if (model.rows!=null) {
              setState(() {
                dataList = model.rows??<MedicalElderInfo>[];
                for (var item in (model.rows??<MedicalElderInfo>[])) {
                  dataChartList.add(
                    ChartData(
                      DateUtil.formatDateStr(
                        item.collectionTime??"",
                        format: queryTimeType == 1
                            ? DateFormats.h_m
                            : DateFormats.mo_d,
                      ),
                      item.number??0,
                    ),
                  );
                }
              });
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
